package com.program.facesigninsystem.controller;

import cn.yueshutong.springbootstartercurrentlimiting.annotation.CurrentLimiter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.program.facesigninsystem.dto.ExcelParam;
import com.program.facesigninsystem.entity.*;
import com.program.facesigninsystem.iteration.dto.ExportParam;
import com.program.facesigninsystem.iteration.dto.NoSignInParam;
import com.program.facesigninsystem.iteration.entity.*;
import com.program.facesigninsystem.iteration.mapper.*;
import com.program.facesigninsystem.service.*;
import com.program.facesigninsystem.service.impl.SignInRecordService;
import com.program.facesigninsystem.service.impl.WebSocketServer;
import com.program.facesigninsystem.util.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Mapler
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/rec")
public class SignInRecordController {
    private static Logger log = Logger.getLogger(SignInRecordController.class.toString());


    @Autowired
    ISignInActivityService iSignInActivityService;
    @Autowired
    ISignInRecordService iSignInRecordService;
    @Autowired
    IRewardService iRewardService;
    @Autowired
    ISignInTypeService iSignInTypeService;
    @Autowired
    public IUserInfoService iUserService;
    @Autowired
    public IUserClassService iUserClassService;
    @Autowired
    public IClassesService iClassesService;
    @Autowired
    SignInClassService signInClassService;
    @Resource
    SigninclassMapper signinclassMapper;
    @Resource
    UserSigninclassMapper userSigninclassMapper;
    @Resource
    SigninrecordMapper signinrecordMapper;
    @Resource
    SigninlinkMapper signinlinkMapper;
    @Resource
    SigninactivityMapper signinactivityMapper;
    @Resource
    SignInRecordService signInRecordService;


    @ApiOperation("教师获取已签到成员名单")
    @GetMapping("/resultTeacher")
    @CurrentLimiter(QPS = 5)
    public ResponseModel resultTeacher(@ApiParam(value = "签到环节ID",required = true)@RequestParam("lid") String lid) {
        ResponseModel responseModel;
        try {
            List<Map<String, Object>> recordList = iSignInRecordService.selectRecordList(lid);
            for (Map<String, Object> map : recordList) {
                Object value = map.get("signintime");
                ChangeDate changeDate = new ChangeDate();
                changeDate.setSettime(value.toString());
                map.put("signintime", changeDate.getSettime());
                map.putIfAbsent("state", "");
                // 确保包含 student_id
                map.putIfAbsent("student_id", "");
            }
            SignInActivity signInActivity = iSignInActivityService.selectAct(lid);
            String title = signInActivity.getTitle();
            int count = iSignInRecordService.selectRecCount(lid);
            SigninclassEntity signinclassEntity = signInClassService.selectClassbylid(lid);
            ArrayList<Object> data = new ArrayList<>();
            data.add(0, title);
            Map<String, Object> map = new HashMap<>(1);
            map.put("已签到", count);
            data.add(1, map);
            data.add(2, recordList);
            if (signinclassEntity != null) {
                data.add(3, signinclassEntity.getName());
                data.add(4, signinclassEntity.getNumber());
            } else {
                data.add(3, "");
                data.add(4, "");
            }
            SignInLink signInLink=iSignInActivityService.selectLinkByLid(lid);
            data.add(5,signInLink.getLinkType());
            data.add(6,signInActivity.getSignStopType());
            data.add(7,signInLink.getEndTime());
            ChangeDate changeDate = new ChangeDate();
            Date date = new Date(System.currentTimeMillis());
            changeDate.setSettime(signInLink.getEndTime());
            if (signInLink.getEndTime() !=null && !signInLink.getEndTime().equals("") && date.after(changeDate.settime) && !signInLink.getEndTime().equals(signInLink.getStartTime())) {
                signInLink.setStatus(2);
            }
            data.add(8,signInLink.getStatus());
            responseModel = new ResponseModel(200, "获取成功", data);
        } catch (Exception e) {
            responseModel = new ResponseModel(199, "获取失败");
        }
        return responseModel;
    }

    @ApiOperation("获取正在签到各种信息")
    @GetMapping("/resultTeacher3")
    @CurrentLimiter(QPS = 5)
    public ResponseModel resultTeacher3(@ApiParam(value = "签到环节ID",required = true)@RequestParam("ccid") String ccid) {
        ResponseModel responseModel;
        try {
            String lid=iSignInActivityService.selectnowlidbyccid(ccid);
            if(lid==null){
                responseModel = new ResponseModel(198, "无正在进行的考勤");
                return responseModel;
            }
            List<Map<String, Object>> recordList = iSignInRecordService.selectRecordList(lid);
            for (Map<String, Object> map : recordList) {
                Object value = map.get("signintime");
                ChangeDate changeDate = new ChangeDate();
                changeDate.setSettime(value.toString());
                map.put("signintime", changeDate.getSettime());
                map.putIfAbsent("state", "");
            }
            SignInActivity signInActivity = iSignInActivityService.selectAct(lid);
            String title = signInActivity.getTitle();
            int count = iSignInRecordService.selectRecCount(lid);
            int qiandao=iSignInRecordService.selectRecCount1(lid,1);
            int qingjia=iSignInRecordService.selectRecCount1(lid,2);
            int chidao=iSignInRecordService.selectRecCount1(lid,3);
            int qita=iSignInRecordService.selectRecCount1(lid,4);
            int weirenzheng=iSignInRecordService.selectRecCount1(lid,5);
            int kuangke=iSignInRecordService.selectRecCount1(lid,6);
            SigninclassEntity signinclassEntity = signInClassService.selectClassbylid(lid);
            ArrayList<Object> data = new ArrayList<>();
            data.add(0, title);
            Map<String, Object> map = new HashMap<>(1);
            map.put("已签到", count);
            map.put("签到", qiandao);
            map.put("请假", qingjia);
            map.put("迟到", chidao);
            map.put("其他", qita);
            map.put("未认证", weirenzheng);
            map.put("旷课", kuangke);
            data.add(1, map);
            data.add(2, recordList);
            if (signinclassEntity != null) {
                data.add(3, signinclassEntity.getName());
                data.add(4, signinclassEntity.getNumber());
            } else {
                data.add(3, "");
                data.add(4, "");
            }
            SignInLink signInLink=iSignInActivityService.selectLinkByLid(lid);
            data.add(5,signInLink.getLinkType());
            data.add(6,signInActivity.getSignStopType());
            data.add(7,signInLink.getEndTime());
            ChangeDate changeDate = new ChangeDate();
            Date date = new Date(System.currentTimeMillis());
            changeDate.setSettime(signInLink.getEndTime());
            if (signInLink.getEndTime() !=null && !signInLink.getEndTime().equals("") && date.after(changeDate.settime) && !signInLink.getEndTime().equals(signInLink.getStartTime())) {
                signInLink.setStatus(2);
            }
            data.add(8,signInLink.getStatus());
            SigninlinkEntity signinlinkEntity = signinlinkMapper.selectOne(new QueryWrapper<SigninlinkEntity>().eq("lid", lid));
            SigninactivityEntity signinactivityEntity = signinactivityMapper.selectOne(new QueryWrapper<SigninactivityEntity>().eq("actid", signinlinkEntity.getActid()));
            List<NoSignInParam> noSignInParamList = signInRecordService.getNoSignIn(lid, signinactivityEntity.getCid());
            data.add(9,noSignInParamList);
            responseModel = new ResponseModel(200, "获取成功", data);
        } catch (Exception e) {
            responseModel = new ResponseModel(199, "无正在进行的考勤");
        }
        return responseModel;
    }
    @ApiOperation("获取正在签到各种信息")
    @GetMapping("/isresultTeacher")
    @CurrentLimiter(QPS = 5)
    public ResponseModel isresultTeacher(@ApiParam(value = "签到环节ID",required = true)@RequestParam("ccid") String ccid) {
        ResponseModel responseModel;
        try {
            String lid=iSignInActivityService.selectnowlidbyccid(ccid);
            if(lid==null){
                responseModel = new ResponseModel(198, "无正在进行的考勤");
                return responseModel;
            }
            responseModel = new ResponseModel(200, "获取成功");
        } catch (Exception e) {
            responseModel = new ResponseModel(199, "无正在进行的考勤");
        }
        return responseModel;
    }

    @ApiOperation("教师获取未签到成员名单")
    @GetMapping("/resultTeacher2")
    @CurrentLimiter(QPS = 5)
    public ResponseModel resultTeacher2(@ApiParam(value = "签到环节ID",required = true)@RequestParam("lid") String lid) {
        ResponseModel responseModel;
        try {
            SigninlinkEntity signinlinkEntity = signinlinkMapper.selectOne(new QueryWrapper<SigninlinkEntity>().eq("lid", lid));
            SigninactivityEntity signinactivityEntity = signinactivityMapper.selectOne(new QueryWrapper<SigninactivityEntity>().eq("actid", signinlinkEntity.getActid()));
            List<NoSignInParam> noSignInParamList = signInRecordService.getNoSignIn(lid, signinactivityEntity.getCid());

            responseModel = new ResponseModel(200, "获取成功", noSignInParamList);
        } catch (Exception e) {
            responseModel = new ResponseModel(199, "获取失败");
        }
        return responseModel;
    }
    @ApiOperation("获取未签到成员名单")
    @GetMapping("/noSignInTea")
    @CurrentLimiter(QPS = 5)
    public ResponseModel noSignInTea(@ApiParam("签到环节ID")@RequestParam("lid") String lid) {
        SignInActivity signInActivity = iSignInActivityService.selectAct(lid);
        String cid = signInActivity.getCid();
        ResponseModel responseModel;
        if (!"".equals(cid)) {
            List<UserSigninclassEntity> userSigninclassEntityList = signInClassService.getMember(Integer.parseInt(cid));
            if (userSigninclassEntityList == null) {
                return new ResponseModel(198, "名单中无成员");
            }
            if (userSigninclassEntityList.size() != 0) {
                try {
                    List<Map<String, Object>> userList = iSignInRecordService.selectNoSignIn(cid, lid);
                    String title = signInActivity.getTitle();
                    int count = userSigninclassEntityList.size() - iSignInRecordService.selectRecCount(lid);
                    ArrayList<Object> data = new ArrayList<>();
                    data.add(0, title);
                    Map<String, Object> map = new HashMap<>(1);
                    map.put("未签到", count);
                    data.add(1, map);
                    data.add(userList);
                    responseModel = new ResponseModel(200, "获取成功", data);
                } catch (Exception e) {
                    responseModel = new ResponseModel(199, "获取失败");
                }
            } else {
                responseModel = new ResponseModel(198, "名单中无成员");
            }
        } else {
            responseModel = new ResponseModel(197, "无名单");
        }
        return responseModel;
    }
    @ApiOperation("新增签到环节")
    @GetMapping("/addNewRecord")
    @CurrentLimiter(QPS = 10)
    public ResponseModel addNewRecord(
            @ApiParam(value = "签到环节ID",required = true,example = "07412704444673309641")@RequestParam("lid") String lid,
            @ApiParam(value = "用户ID",required = true,example = "01847918709811115536")@RequestParam("uid") String uid,
            @ApiParam(value = "经度",required = true)@RequestParam("location_x") double locationX,
            @ApiParam(value = "纬度",required = true)@RequestParam("location_y") double locationY,
            @ApiParam(value = "环节当前状态",required = false)@RequestParam(value = "state", required = false, defaultValue = "normal") String state,
            @ApiParam(value = "环节当前状态2",required = false)@RequestParam(value = "state2", required = false, defaultValue = "99") String state2
            ) {
        try {
            SigninlinkEntity signinlinkEntity = signinlinkMapper.selectOne(new QueryWrapper<SigninlinkEntity>().eq("lid", lid));
            SigninactivityEntity signinactivityEntity = signinactivityMapper.selectOne(new QueryWrapper<SigninactivityEntity>().eq("actid", signinlinkEntity.getActid()));
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String id = GetInfoUtil.getId();
            SignInActivity signInActivity = iSignInActivityService.selectAct(lid);
            String tid = signInActivity.getTid();
            Rewards rewards = iRewardService.selectReward(uid);
            Rewards rewardsTeacher = iRewardService.selectReward(tid);
            String cid = signInActivity.getCid();
            UserSigninclassEntity userSigninclassEntity = null;
            Map<String, Object> map = iUserService.selectUser(uid);
            String userName = map.get("name") == null ? "" : map.get("name").toString();
            String avatar = map.get("avatar") == null ? "" : map.get("avatar").toString();
            if (!"".equals(cid)) {
                userSigninclassEntity = userSigninclassMapper.selectOne(new QueryWrapper<UserSigninclassEntity>()
                        .eq("signinclass_id", cid)
                        .eq("name", userName));
            }
            if ("".equals(cid) || userSigninclassEntity != null) {
                SignInRecord signInRecord = iSignInRecordService.selectRecExist(uid, lid);
                if (signInRecord == null) {
                    SignInLink signInLink = iSignInActivityService.selectLinkByLid(lid);
                    ChangeDate changeDate = new ChangeDate();
                    if (signInLink.getEndTime() != null)
                        changeDate.setSettime(signInLink.getEndTime());
                    Date date = new Date(System.currentTimeMillis());
                    String createTime = dateFormat.format(System.currentTimeMillis());
                    if (signInLink.getEndTime()!=null && !date.before(changeDate.settime)) {

                        WebSocketServer.sendMessage("{\"name\":\"" + userName + "\",\"avatar\":\"" + avatar + "\",\"lid\":\"" + lid + "\"}", tid);
                        if (signinactivityEntity.getSignStopType() != null) {
                            if (signinactivityEntity.getSignStopType() == 0) {
                                iSignInRecordService.signinByTea(id, uid, lid, createTime, "迟到");
                                return new ResponseModel(200, "签到成功，已迟到");
                            } else {
                                iSignInRecordService.signinByTea(id, uid, lid, createTime, "签到");
                                return new ResponseModel(200, "签到成功");
                            }
                        }

                        return new ResponseModel(200, "签到成功，已迟到");
                    }
                    if (signInLink.getLocation_x() != 0 && signInLink.getLocation_y() != 0 && signInLink.getRangement() != 0) {
                        if (locationX != 0 && locationY != 0) {
                            double distance = LocationUtil.algorithm(signInLink.getLocation_x(), signInLink.getLocation_y(), locationX, locationY);
                            if (distance > signInLink.getRangement()) {
                                return new ResponseModel(165, "签到失败,未在签到范围内");
                            }
                        } else {
                            return new ResponseModel(164, "签到失败,未传坐标");
                        }
                    }

                    iSignInRecordService.addNewRecord(id, lid, uid, createTime, state,state2);
                    String currentDay = dateFormat.format(System.currentTimeMillis()).substring(0, 10);
                    WebSocketServer.sendMessage("{\"name\":\"" + userName + "\",\"avatar\":\"" + avatar + "\",\"lid\":\"" + lid + "\"}", tid);
                    return addReward(rewardsTeacher, rewards, uid, currentDay, tid);
                } else {
                    return new ResponseModel(198, "您已签到");
                }
            } else {
                return new ResponseModel(199, "您未在签到名单中");
            }
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
            return new ResponseModel(169, "签到失败");
        }
    }
    @ApiOperation("教师代签")
    @GetMapping("/recByTea")
    public ResponseModel addRecByTea(@ApiParam(value = "被代签用户ID",required = true)@RequestParam("uid") String uid, @ApiParam(value = "签到环节ID",required = true)@RequestParam("lid") String lid, @ApiParam(value = "签到状态",required = true)@RequestParam("state") String state) {
        try {
            String id = GetInfoUtil.getId();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createTime = dateFormat.format(System.currentTimeMillis());
            iSignInRecordService.signinByTea(id, uid, lid, createTime, state);
            return new ResponseModel(200, "代签成功");
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
            return new ResponseModel(169, "代签失败");
        }
    }

    @ApiOperation("教师代签2")
    @GetMapping("/recByTea2")
    public ResponseModel addRecByTea2(@RequestParam("name") String name, @RequestParam("lid") String lid, @RequestParam("state") String state) {
        try {
            String id = GetInfoUtil.getId();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createTime = dateFormat.format(System.currentTimeMillis());
            iSignInRecordService.signinByTea2(id, name, lid, createTime, state);
            return new ResponseModel(200, "代签成功");
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
            return new ResponseModel(169, "代签失败");
        }
    }
    @ApiOperation("按日期查询签到记录")
    @GetMapping("/selectRecord")
    @CurrentLimiter(QPS = 5)
    public ResponseModel selectRecord(@ApiParam(value = "日期" ,required = false)@RequestParam(value = "date", required = false) String date, @ApiParam(value = "用户ID",required = true)@RequestParam("uid") String uid) {
        try {
            List<SignInRecord> signInRecordList;
            Object[] objects;
            if (date == null) {
                signInRecordList = iSignInRecordService.selectRecordAll(uid);
                objects = signInRecordList.toArray();
            } else {
                String date1 = date + " 00:00:00";
                String date2 = date + " 23:59:59";
                signInRecordList = iSignInRecordService.selectRecord(uid, date1, date2);
                objects = signInRecordList.toArray();
            }
            return new ResponseModel(200, "获取成功", objects);
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
            return new ResponseModel(168, "获取失败");
        }
    }

    @ApiOperation("按月查询记录")
    @GetMapping("/selectRecordByMonth")
    public ResponseModel selectRecordByMonth(@ApiParam(value = "用户ID",required = true)@RequestParam("uid") String uid, @ApiParam(value = "月份",required = true,example = "2022-03-01 18:21:18")@RequestParam("month") String month) {
        try {
            List<Integer> outDays = new ArrayList<>();
            List<SignInRecord> days = iSignInRecordService.selectRecordByMonth(uid, month);
            System.out.println(days);
            Iterator iterator = days.iterator();
            int day;
            SignInRecord signInRecord;
            while (iterator.hasNext()) {
                signInRecord = (SignInRecord) iterator.next();
                day = Integer.parseInt(signInRecord.getSignintime().toString().substring(8, 10));
                if (!outDays.contains(day)) {
                    outDays.add(day);
                }
            }
            return new ResponseModel(200, "获取成功", outDays);
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
            return new ResponseModel(139, "获取失败");
        }
    }

    @GetMapping("/selectRank")
    public ResponseModel selectRank() {
        try {
            return new ResponseModel(200, "获取成功", iSignInRecordService.selectRank());
        } catch (Exception e) {
            return new ResponseModel(129, "获取失败");
        }
    }
    @ApiOperation("用户按日期查询待签到")
    @GetMapping("/selectMyRecord")
    @CurrentLimiter(QPS = 5)
    public ResponseModel selectMyRecord(@ApiParam(value = "用户ID",required = true) @RequestParam("uid") String uid, @ApiParam(value = "日期",required = true)@RequestParam("date") String date) {
        try {
            return new ResponseModel(200, "获取成功", iSignInRecordService.selectMyRecord(uid, date));
        } catch (Exception e) {
            return new ResponseModel(128, "获取失败");
        }
    }
    @ApiOperation("查询签到结果(分页、有序)")
    @GetMapping("/selectList")
    public void selectList(HttpServletResponse resp, @ApiParam(value = "签到环节ID",required = true)@RequestParam(value = "lid") String lid,
                           @ApiParam(value = "分页的页数",required = true)@RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                           @ApiParam(value = "每页内容的数量",required = true)@RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize) {
        try {
            List<Map<String, Object>> mapList = iSignInRecordService.selectList(lid);
            try {
                JSONObject jsonObject = PageUtil.wrap2(mapList, "Record", pageSize, pageNum);
                /*设置编码，防止出现乱码问题*/
                resp.setCharacterEncoding("utf-8");
                /*得到输出流*/
                PrintWriter respWriter = resp.getWriter();
                /*将JSON格式的对象toString()后发送*/
                respWriter.append(jsonObject.toString());
            } catch (Exception e) {
                log.log(Level.SEVERE, "Error parsing date", e);
            }
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
        }
    }

    @PostMapping("/excel")
    @CurrentLimiter(QPS = 5)
    public void exportCorpLoanDemand(@RequestBody ExcelParam excelParam,
                                     HttpServletRequest request,
                                     HttpServletResponse response) {
        try {
            SignInActivity signInActivity = iSignInActivityService.selectAct(excelParam.getLid());
            String actTitle = signInActivity.getTitle();
            String linkName = iSignInTypeService.selectName(excelParam.getLid());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = dateFormat.format(System.currentTimeMillis());
            String fileName = actTitle + "+" + linkName + "+" + time + ".xls";
            iSignInRecordService.exportExcel(fileName, excelParam.getLid(), request, response, excelParam.getNoSignIn());
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
        }
    }

    @PostMapping("/excel2")
    @CurrentLimiter(QPS = 5)
    public void exportCorpLoanDemand2(@RequestBody String lid,
                                      HttpServletRequest request,
                                      HttpServletResponse response) {
        try {
            log.info(lid);
            SignInActivity signInActivity = iSignInActivityService.selectAct(lid);
            String actTitle = signInActivity.getTitle();
            String linkName = iSignInTypeService.selectName(lid);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = dateFormat.format(System.currentTimeMillis());
            String fileName = actTitle + "+" + linkName + "+" + time + ".xls";
            iSignInRecordService.exportExcel2(fileName, lid, request, response);
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
        }
    }

    @GetMapping("/excelJYK")
    @CurrentLimiter(QPS = 5)
    public void exportCorpLoanDemandJYK(@RequestParam String lid,
                                        @RequestParam List<Map<String, String>> noSignIn,
                                        HttpServletRequest request,
                                        HttpServletResponse response) {
        try {
            SignInActivity signInActivity = iSignInActivityService.selectAct(lid);
            String actTitle = signInActivity.getTitle();
            String linkName = iSignInTypeService.selectName(lid);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String time = dateFormat.format(System.currentTimeMillis());
            String fileName = actTitle + "+" + linkName + "+" + time + ".xls";
            iSignInRecordService.exportExcel(fileName, lid, request, response, noSignIn);
        } catch (Exception e) {
            log.log(Level.SEVERE, "Error parsing date", e);
        }
    }

    private ResponseModel addReward(Rewards rewardsTeacher, Rewards rewards, String uid, String currentDay, String tid) {
        String lastGainDay;
        int a = rewardsTeacher.getLimit_from_record_a();
        int b = rewardsTeacher.getLimit_from_record_b();
        int c = rewardsTeacher.getLimit_from_record_c();
        int activity = rewardsTeacher.getLimit_from_activity();
        //学生签到成功，教师加2分
        int dayMaxRewards = 100;
        if (rewardsTeacher.getDay_reward() < dayMaxRewards) {
            int rewardPerTimeForTea = 2;
            iRewardService.updateRewards(tid, a, b, c, activity, currentDay,
                    rewardsTeacher.getReward_points() + rewardPerTimeForTea,
                    rewardsTeacher.getDay_reward() + rewardPerTimeForTea
            );
        }
        //有则更新记录
        int rewardPerTime = 30;
        if (rewards != null) {
            int limitFromRecordActivity = rewards.getLimit_from_activity();
            lastGainDay = rewards.getLast_gain_day();
            int rewardPoint = rewards.getReward_points();
            if (!lastGainDay.equals(currentDay)) {
                //如果上次获取积分的日期不等于今天，则直接加上积分，并将上次获取积分的日期改为今天
                iRewardService.updateRewards(uid, 1, 0, 0,
                        0, currentDay, rewardPoint + rewardPerTime, rewardPerTime);
                return new ResponseModel(200, "签到成功", "积分 +30");
            }
            //如果今日获取积分已达上限
            if (dayMaxRewards < rewards.getDay_reward()) {
                return new ResponseModel(200, "签到成功", "今日获取总积分已达上限");
            }
            //判断是不是今天第一次获取
            else if (rewards.getLimit_from_record_a() == 0) {
                iRewardService.updateRewards(
                        uid, 1, 0, 0, limitFromRecordActivity, currentDay,
                        rewardPoint + rewardPerTime, rewards.getDay_reward() + rewardPerTime);
            }
            //判断是不是今天第二次获取
            else if (rewards.getLimit_from_record_b() == 0) {
                iRewardService.updateRewards(
                        uid, 1, 1, 0, limitFromRecordActivity, currentDay,
                        rewardPoint + rewardPerTime, rewards.getDay_reward() + rewardPerTime);
            }
            //判断是不是今天第三次获取
            else if (rewards.getLimit_from_record_c() == 0) {
                iRewardService.updateRewards(
                        uid, 1, 1, 1, limitFromRecordActivity, currentDay,
                        rewardPoint + rewardPerTime, rewards.getDay_reward() + rewardPerTime
                );
            } else {
                return new ResponseModel(200, "签到成功", "今日签到获取积分次数已达上限");
            }
            return new ResponseModel(200, "签到成功", "积分 +30");
        }
        //无记录新增积分记录
        iRewardService.addNewRewards(uid, 1, 0, 0, 0,
                currentDay, rewardPerTime, rewardPerTime
        );
        return new ResponseModel(200, "签到成功", "积分 +30");
    }

    /***
     * 对比名单
     * @return ResponseModel
     */
    @ApiOperation("对比名单")
    @GetMapping("/contrast")
    public ResponseModel contrast(@ApiParam(value = "名单文件路径",required = true)@RequestParam("filePath") String filePath, @ApiParam(value = "签到环节ID",required = true)@RequestParam("lid") String lid) {
        File file = new File(filePath);
        int lastIndexOf = filePath.lastIndexOf(".");
        String suffix = filePath.substring(lastIndexOf + 1);
        String repeatname = "";
        if (!file.exists()) {
            return new ResponseModel(198, "名单不存在");
        } else {
            try {
                List<Map<String, Object>> recordList = iSignInRecordService.selectRecordList(lid);
                HashMap maplist = new HashMap();
                List<String> namelist = new ArrayList<>();
                List<String> numberlist = new ArrayList<>();
                List<Map<String, String>> noSignin = new ArrayList<>();
                List excelList;
                List excelList_bindid;
                switch (suffix) {
                    case "xls":
                        maplist = ExcelUtil.readXlsx_bingid(file);
//                        excelList = ExcelUtil.readXls(file);
//                        excelList_bindid = ExcelUtil.readXls_bindid(file);
                        break;
                    case "xlsx":
//                        excelList = ExcelUtil.readXlsx(file);
//                        excelList_bindid = ExcelUtil.readXlsx_bingid(file);
                        maplist = ExcelUtil.readXlsx_bingid(file);
                        break;
                    default:
                        return new ResponseModel(197, "文件格式不支持");
                }
//                if (excelList == null) {
//                    return new ResponseModel(190, "文件第一行不存在关键字“姓名”");
//                }
                if (maplist == null) {
                    return new ResponseModel(190, "文件第一行不存在关键字“姓名”");
                }
                for (Map<String, Object> map : recordList) {
                    Object value = map.get("name");
                    namelist.add(value.toString());
                    Object value2 = map.get("bindid");
                    numberlist.add(value2.toString());
                }
//                for (Object anExcelList : excelList) {
//                    List list = (List) anExcelList;
//                    for (Object aList : list) {
//                        boolean f = namelist.contains(aList.toString());
//                        if (!f) {
//                            Map<String, String> unSign = new HashMap<>(1);
//                            unSign.put("name", aList.toString());
//                            noSignin.add(unSign);
//                        }
//                    }
//                }
                Iterator it = maplist.keySet().iterator();
                while (it.hasNext()) {
                    Object name = it.next();
                    int count = frequency(namelist, name.toString());
                    if (count >= 2) {
                        Object number = maplist.get(name);
                        if (numberlist.contains(number.toString())) {
                            continue;
                        } else {
                            repeatname = name.toString();
                        }
                    }
                    if (count == 0) {
                        Map<String, String> unSign = new HashMap<>(1);
                        unSign.put("name", name.toString());
                        noSignin.add(unSign);
                    }
                }
                return new ResponseModel(200, "对比成功", noSignin);
            } catch (Exception e) {
                return new ResponseModel(199, "对比失败");
            }
        }
    }

    private static int frequency(List<String> list, String string) {
        int count = 0;

        for (String s : list) {
            if (string.equals(s)) {
                count++;
            }

        }
        return count;


    }

    /***
     * 对比名单
     * @return ResponseModel
     */
    @ApiOperation("对比名单2")
    @GetMapping("/contrast2")
    public ResponseModel contrast(@ApiParam(value = "名单ID",required = true)@RequestParam int listId,
                                  @ApiParam(value = "名单ID",required = true)@RequestParam String linkId) {

        SigninclassEntity signinclassEntity = signinclassMapper.selectById(listId);
        String repeatname = "";
        if (signinclassEntity == null) {
            return new ResponseModel(198, "名单不存在");
        } else {
            try {
                List<Map<String, Object>> recordList = iSignInRecordService.selectRecordList(linkId);
                List<String> namelist = new ArrayList<>();
//                List<String> numberlist = new ArrayList<>();
                List<Map<String, String>> noSignin = new ArrayList<>();
                List<String> excelList = new ArrayList<>();
                HashMap maplist = new HashMap();
                List<UserSigninclassEntity> userSigninclassEntityList = userSigninclassMapper.selectList(new QueryWrapper<UserSigninclassEntity>().eq("signinclass_id", signinclassEntity.getId()));
                for (UserSigninclassEntity userSigninclassEntity : userSigninclassEntityList) {
                    //excelList.add(userSigninclassEntity.getName());
                    maplist.put(userSigninclassEntity.getName(), userSigninclassEntity.getSigninclassNumber().toString());
                }
                for (Map<String, Object> map : recordList) {
                    Object value = map.get("name");
                    namelist.add(value.toString());
//                    Object value2 = map.get("bindid");
//                    numberlist.add(value2.toString());
                }
//                for (String name : excelList) {
//                    boolean f = namelist.contains(name);
//                    if (!f) {
//                        Map<String, String> unSign = new HashMap<>(1);
//                        unSign.put("name", name);
//                        noSignin.add(unSign);
//                    }
//
//                }
                Iterator it = maplist.keySet().iterator();
                while (it.hasNext()) {
                    Object name = it.next();
                    int count = frequency(namelist, name.toString());
                    if (count >= 2) {
//                        Object number = maplist.get(name);
//                        if (numberlist.contains(number.toString())) {
//                            continue;
//                        } else {
                            repeatname = name.toString();
//                        }
                    }
                    if (count == 0) {
                        Map<String, String> unSign = new HashMap<>(1);
                        unSign.put("name", name.toString());
                        noSignin.add(unSign);
                    }
                }
                if (!repeatname.equalsIgnoreCase("")) {
                    return new ResponseModel(200, "重复姓名警告，请" + repeatname + "同学添加学号", noSignin);
                }
                return new ResponseModel(200, "对比成功", noSignin);
            } catch (Exception e) {
                return new ResponseModel(199, "对比失败");
            }
        }
    }
    @ApiOperation("获取一次签到环节的签到情况")
    @GetMapping("/selectDistinctState")
    public ResponseModel selectDistinctState(@ApiParam(value = "签到环节ID",required = true)@RequestParam("lid") String lid) {
        return iSignInRecordService.selectDistinctState(lid);
    }
    @ApiOperation("修改用户签到状态")
    @GetMapping("/setSignInState")
    public ResponseModel setSignInState(@ApiParam(value = "被修改用户ID",required = true)@RequestParam("uid") String uid, @ApiParam(value = "签到状态",required = true)@RequestParam("state") String state, @ApiParam(value = "签到环节ID",required = true)@RequestParam("lid") String lid) {
        return iSignInRecordService.setSignInState(uid, lid, state);
    }


    @ApiOperation("选择多个签到活动一起导出签到记录")
    @PostMapping("/exportSignInRecord")
    public void exportSignInRecord(@ApiParam(value="actIdList : 签到活动ID ,\n signInClassId : 签到名单ID,\n titleList : 标题名称列表 示例: 0:签到次数 1:未签到次数")@RequestBody ExportParam exportParam,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {

        iSignInRecordService.exportSignInRecord(exportParam.getActIdList(), exportParam.getSignInClassId(), exportParam.getTitleList(), request, response);
    }

}
